<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import MarkdownIt from 'markdown-it'
  import hljs from 'highlight.js'
  import 'highlight.js/styles/github-dark.min.css'
  // @ts-ignore
  import 'github-markdown-css/github-markdown-light.css'
  import markdownItAnchor from 'markdown-it-anchor'
  import { message } from 'ant-design-vue'
  const props = defineProps<{ content: string }>()
  // const content = '/static/upload/aboutApp20250809.md'
  const bodyHtml = ref('')

  const md = new MarkdownIt({
    html: false, // 禁用内联 HTML（推荐）
    linkify: true, // 安全链接化
    breaks: true,
    highlight: (code, lang) => {
      // 代码高亮处理
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(code, { language: lang }).value
        } catch (_) {}
      }
      return ''
    },
  })

  // 安全链接插件
  const secureLinkPlugin = (md: any) => {
    md.renderer.rules.link_open = (tokens: any, idx: any) => {
      const href = tokens[idx].attrGet('href')
      if (href.startsWith('javascript:')) {
        tokens[idx].attrSet('href', '#') // 拦截危险协议
      }
      return '<a target="_blank" rel="noopener noreferrer">'
    }
  }

  md.use(markdownItAnchor, {
    permalink: markdownItAnchor.permalink.linkInsideHeader({
      symbol: '',
      placement: 'after',
      class: 'header-anchor',
    }),
  }).use(secureLinkPlugin)

  // 读取远程文件（需解决跨域）
  const loadRemoteMd = async () => {
    if (!props.content) return
    try {
      const response = await fetch(
        `${import.meta.env.VITE_APP_BASE_API}${props.content}`
      )
      const text = await response.text()

      // 渲染带 TOC 的 HTML
      const htmlWithToc = md.render(text)
      bodyHtml.value = htmlWithToc
    } catch (error) {
      message.error('加载失败')
    }
  }

  onMounted(() => {
    loadRemoteMd()
  })
</script>
<template>
  <div
    class="markdown-body"
    v-html="bodyHtml"
  ></div>
</template>

<style scoped lang="less"></style>
